/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { DownOutlined } from '@ant-design/icons';
import { Tabs, Swiper, Popup, Ellipsis } from 'antd-mobile';
import { SwiperRef } from 'antd-mobile/es/components/swiper';
import classNames from 'classnames';
import { isArray, isFunction } from 'lodash';
import React, { useEffect, useMemo, useRef, useState } from 'react';

import styles from './index.less';
import {
  AreaDataItem,
  AreaDataType,
  formatAreaList,
  findListByParent,
  TabItem,
  formatListBeforeSet,
  defaultTabItemTitle,
  createTabList,
  valueKeys,
} from './_utils';

export type CitiesDrawerValue = string[] | null;

interface CitiesDrawerProps {
  type?: AreaDataType;
  value?: CitiesDrawerValue;
  onChange?: (value: CitiesDrawerValue) => void;
  placeholder?: string;
  maxWidth?: number | 'auto';
}

interface CitiesDrawerRefCurrent {
  list: AreaDataItem[];
}

const CitiesDrawer: React.FC<CitiesDrawerProps> = (props) => {
  const { type, value: propsValue, placeholder = '请选择', maxWidth = 100, onChange } = props;
  const actionRef = useRef<CitiesDrawerRefCurrent>({ list: [] });
  const [open, setOpen] = useState(false);
  const [province, setProvince] = useState<AreaDataItem[]>([]);
  const [city, setCity] = useState<AreaDataItem[]>([]);
  const [district, setDistrict] = useState<AreaDataItem[]>([]);
  const [value, setValue] = useState<CitiesDrawerValue>();
  const [tabItems, setTabItems] = useState<TabItem[]>([
    { key: 'province', title: defaultTabItemTitle },
  ]);
  const swiperRef = useRef<SwiperRef>(null);
  const [activeIndex, setActiveIndex] = useState(0);

  // 展示的内容
  const valueLabel = useMemo(() => {
    if (!isArray(value)) return '';
    const index = valueKeys.findIndex((item) => item === type);
    if (index >= 0) {
      return value[index];
    }
    return value.join('-');
  }, [value, type]);

  const cities = useMemo(() => {
    return [province, city, district];
  }, [province, city, district]);

  // 触发change
  const triggerChange = (list: TabItem[]) => {
    const v = list.map((item) => item.title);
    setValue(v);
    if (isFunction(onChange)) {
      onChange(v);
    }
  };

  // 点击选择
  const handleClickItem = (item: TabItem, iitem: AreaDataItem) => {
    const { key: itemKey } = item;
    const isOver = itemKey === 'district' || itemKey === type;
    const list = createTabList(tabItems, itemKey, iitem.value, isOver);
    setTabItems(list);
    if (isOver) {
      // 点击最后一个，或者指定的type
      triggerChange(list);
      setOpen(false);
    } else {
      setActiveIndex(1 + activeIndex);
    }
  };

  // 打开下拉弹窗
  const handleClick = () => setOpen(true);
  // 关闭下拉弹窗
  const handleClose = () => setOpen(false);

  // Swiper切换
  const handleIndexChange = (index: number) => setActiveIndex(index);

  // tab切换
  const handleTabChange = (key: string) => {
    const index = tabItems.findIndex((item) => item.key === key);
    setActiveIndex(index);
  };

  useEffect(() => {
    const list = formatAreaList(window.address, type);
    actionRef.current.list = list;
    // 初始省份
    setProvince(formatListBeforeSet(list));
  }, []);

  // 监听并切换swiper
  useEffect(() => {
    swiperRef.current?.swipeTo(activeIndex);
  }, [activeIndex]);

  // value变更
  useEffect(() => {
    if (!open) return;
    const val = value || [''];
    if (val) {
      setTabItems(
        val.map((cur, index) => ({
          key: valueKeys[index],
          title: cur || defaultTabItemTitle,
        })),
      );
      setActiveIndex(val.length - 1);
    }
  }, [value, open]);

  useEffect(() => {
    setValue(propsValue);
  }, [propsValue]);

  // tab变更
  useEffect(() => {
    if (!open) return;
    const [{ title: provinceTitle = '' } = {}, { title: cityTitle = '' } = {}] = tabItems;
    const { list } = actionRef.current;
    const cityList = findListByParent(list, provinceTitle);
    setCity(formatListBeforeSet(cityList));
    const districtList = findListByParent(cityList, cityTitle);
    setDistrict(formatListBeforeSet(districtList));
  }, [open, tabItems]);

  return (
    <>
      <div className={styles.citiesDrawer} onClick={handleClick}>
        {valueLabel ? (
          <div style={{ maxWidth }}>
            <Ellipsis direction='end' content={valueLabel} />
          </div>
        ) : (
          <div className={styles.citiesDrawerPlaceholder}>{placeholder}</div>
        )}
        <DownOutlined className={styles.citiesDrawerIcon} />
      </div>
      <Popup visible={open} onClose={handleClose} closeOnMaskClick showCloseButton>
        <div className={styles.citiesDrawerTitle}>所在地区</div>
        <Tabs
          activeKey={tabItems[activeIndex].key}
          onChange={handleTabChange}
          stretch={false}
          className={styles.citiesDrawerTab}
        >
          {tabItems.map((item) => (
            <Tabs.Tab title={item.title} key={item.key} />
          ))}
        </Tabs>
        <Swiper
          direction='horizontal'
          loop
          indicator={() => null}
          ref={swiperRef}
          onIndexChange={handleIndexChange}
          defaultIndex={activeIndex}
        >
          {tabItems.map((item, index) => (
            <Swiper.Item key={item.key}>
              <div className={styles.citiesDrawerList}>
                {cities[index].map((iitem) => (
                  <div
                    key={iitem.value}
                    className={classNames(styles.citiesDrawerListItem, {
                      [styles.citiesDrawerListItemActive]: iitem.value === item.title,
                    })}
                    onClick={handleClickItem.bind(null, item, iitem)}
                  >
                    {iitem.label}
                  </div>
                ))}
              </div>
            </Swiper.Item>
          ))}
        </Swiper>
      </Popup>
    </>
  );
};

export default CitiesDrawer;
